package com.car.gatway.exception;

import cn.hutool.json.JSONUtil;
import com.car.commons.core.model.Result;
import com.car.commons.core.model.WoniuException;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GlobleExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        Result<?> result = Result.getResult();
        if(ex instanceof WoniuException) {
            WoniuException me = (WoniuException)ex;
            result.setMsg(me.getMessage()).setCode(me.getCode());
        } else if(ex instanceof Exception)
            result.setCode(500).setMsg("系统错误");
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        String json = JSONUtil.parse(result).toString();
        return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
            return  exchange.getResponse().bufferFactory().wrap(json.getBytes());
        }));
    }

}
